
//  CityTableViewController.m
//  bh
//
//  Created by lanou on 15/12/22.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "CityTableViewController.h"

#import <CoreLocation/CoreLocation.h>

@interface CityTableViewController ()<CLLocationManagerDelegate>

{
    CLLocationManager *_locationManager;
    CLGeocoder *_geocoder;
}


@property (nonatomic,retain) UISearchBar *searchBar;

@property (nonatomic,retain) NSString *location;

@property (nonatomic,assign) double longitude;

@property (nonatomic,assign) double latitude;


@end

@implementation CityTableViewController

- (NSMutableArray *)array
{
    if (!_array) {
        _array = [[NSMutableArray alloc] init];
    }
    return _array;
}

- (NSMutableArray *)array2
{
    if (!_array1) {
        _array1 = [[NSMutableArray alloc] init];
    }
    return _array1;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"城市列表";
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell1"];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"editer_ButtonReturn"] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    
    //定位管理器
    _locationManager=[[CLLocationManager alloc]init];
    
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [_locationManager requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance=10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
    }
    
    
    _geocoder=[[CLGeocoder alloc]init];
   
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
    _longitude = coordinate.longitude;
    _latitude = coordinate.latitude;
    
    [self getAddressByLatitude:_latitude longitude:_longitude];

    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
    
    [self.tableView reloadData];
}


#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        _location  = placemark.addressDictionary[@"City"];

    }];
}






// 返回按钮
- (void)back {
    
    UIControl *vc = (UIControl *)[self.navigationController.view viewWithTag:111];
    vc.alpha = 1.0;
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    
    
    
    if (section == 0 || section == 1 || section == 2) {
        return 1;
    } else if (section == 3) {
        return self.array.count;
    } else {
        return 0;
    }
    
}


// 区头标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
   
    if (section == 0) {
        return nil;
    }
    if (section == 1) {
        return @"当前城市";
    }
    if (section == 2) {
        return @"全部城市";
    } else if (section == 3) {
        return @"热门城市";
    } else {
        return 0;
    }
    
}

// 分区索引
//- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//    
//    
//    
//}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
    
    
    if (indexPath.section == 0) {
         _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0 , 0, kWidth / 5 * 4, 50)];
         _searchBar.placeholder = @"搜索";
         _searchBar.showsSearchResultsButton = YES;
        [cell addSubview:_searchBar];
    }
    
    if (indexPath.section == 1) {
        cell.textLabel.text = [_location stringByAppendingString:@" GPS定位"];
    }
    
    if (indexPath.section == 2) {
        cell.textLabel.text = @"全部";
    }
    else if (indexPath.section == 3){
        
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (int i = 0; i < self.array.count; i ++) {
            CityModel *model = [[CityModel alloc] init];
            model = self.array[i];
            [array addObject:model.name];
        }
        
        cell.textLabel.text = [array objectAtIndex:indexPath.row];
        
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ProfessorViewController *professorVC = [[ProfessorViewController alloc] init];
    
    if (indexPath.section == 1) {
        
        professorVC.city = [_location substringToIndex:2];
        
    }
    
    else {
        
        CityModel *city = [self.array objectAtIndex:indexPath.row];
        
        professorVC.city = city.name;
    }
    
    
    
    professorVC.array3 = self.array;
    
    [self.navigationController pushViewController:professorVC animated:YES];
}






/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
